

import CryptoJS from 'crypto-js'
//节流
export const trottle = (func, time = 1000, context) => {
  let previous = new Date(0).getTime();
  return function (...args) {
    let now = new Date().getTime();
    if (now - previous > time) {
      func.apply(context, args);
      previous = now;
    }
  };
};

//判断是否为微信环境
export function isWeixinClient() {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    //这是微信环境
    return true;
  } else {
    //这是非微信环境
    return false;
  }
}

//判断是否为安卓环境
export function isAndroid() {
  let u = navigator.userAgent;
  return u.indexOf("Android") > -1 || u.indexOf("Adr") > -1;
}

//获取url后的参数  以对象返回
export function strToParams(str) {
  var newparams = {};
  for (let item of str.split("&")) {
    newparams[item.split("=")[0]] = item.split("=")[1];
  }
  return newparams;
}

//重写encodeURL函数
export function urlencode(str) {
  str = (str + "").toString();
  return encodeURIComponent(str)
    .replace(/!/g, "%21")
    .replace(/'/g, "%27")
    .replace(/\(/g, "%28")
    .replace(/\)/g, "%29")
    .replace(/\*/g, "%2A")
    .replace(/%20/g, "+");
}

//一维数组截取为二维数组

export function arraySlice(data, array = [], optNum = 10) {
  data = JSON.parse(JSON.stringify(data));
  if (data.length <= optNum) {
    data.length > 0 && array.push(data);
    return array;
  }
  array.push(data.splice(0, optNum));
  return arraySlice(data, array, optNum);
}

//对象参数转为以？&拼接的字符
export function paramsToStr(params) {
  let p = "";
  if (typeof params == "object") {
    p = "?";
    for (let props in params) {
      p += `${props}=${params[props]}&`;
    }
    p = p.slice(0, -1);
  }
  return p;
}



//无相增加
export function getWeekDates(inDate = "") {  //获取传值日期的周
			  //const today = new Date(); // 获取当前日期
			 // console.log("bbb",today)
			 let today = new Date(); // 获取当前日期
			// let inDate = ""
			  if(inDate){
				  
				 today = new Date(inDate); ///获取传值日期的周
			  }
			 // const today = new Date(); // 获取当前日期
			  
			  //const today = new Date(); // 获取当前日期
			  //console.log("ddd",today)
			  const startDayOfWeek = today.getDay(); // 获取本周的开始日期（周日为0）
				//console.log("ddd",startDayOfWeek)
			  // 存储本周每天的日期
			  const weekDates = [];
			  
			
			  for (let i = 0; i < 7; i++) {
			    // 复制今天的日期
			    let date = new Date(today);
			    // 减去当前天数，得到本周的某一天
			    date.setDate(today.getDate() - startDayOfWeek + i); //从周一开始
			    
			    // 获取月份和日期
				const year = date.getFullYear()
			    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // getMonth() 返回的月份是从0开始的
			    const dateOfMonth = date.getDate().toString().padStart(2, '0');
			    
			    // 格式化月份和日期
			    const formattedDate = `${month}/${dateOfMonth}`;
			    
			    // 星期几的中文名称
			    const daysOfWeek = ['周日','周一', '周二', '周三', '周四', '周五', '周六'];
			    const dayOfWeek = daysOfWeek[i];
			    
			    // 添加到数组
				let tempArr = {
					"date":formattedDate,
					"week":dayOfWeek,
					"fullDate":year + "-" + month + "-" + dateOfMonth
				}
			    weekDates.push(tempArr);
				// if(today.getDate() === date.getDate()){
				// 	break;
				// }
			  }
			  console.log(weekDates)
			  return weekDates;
}

export function secondsToHoursMinutes(seconds) {
			  const hours = Math.floor(seconds / 3600); // 整除得到小时数
			  const remainingSeconds = seconds % 3600; // 取余得到不足一小时的秒数
			  const minutes = Math.floor(remainingSeconds / 60); // 整除得到分钟数
			  const secondsLeft = seconds % 60;
			
			  // 格式化输出结果
			 //  if(hours == 0 && minutes == 0){
				//   return `${seconds}秒`;
			 //  }
			 //  if(hours == 0){
				//   return `${minutes}分钟`;
			 //  }else{
				// return `${hours}小时${minutes}分钟`;  
			 //  }
			  
			  let data = {
				  hours:hours.toString().padStart(2, '0'),
				  minutes:minutes.toString().padStart(2, '0'),
				  seconds:secondsLeft.toString().padStart(2, '0'),
			  }
			  return data
			
			}

export function getToday() {
			    const today = new Date(); // 获取今天的日期
			    //const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000); // 减去7天的时间（以毫秒为单位）
				//console.log("aaa")
				const year = today.getFullYear();
				const month = (today.getMonth() + 1).toString().padStart(2, '0'); // 月份从1开始计数
				const date = today.getDate().toString().padStart(2, '0');
				const todayText = year + "-" + month + "-" + date
				//const todayText = year + "-" + "08" + "-" + 26
				//console.log(year + "-" + month + "-" + date);
			    return todayText;
			  }

export function getHourArr(){
				let halfHourArray = [];
				let tempHour = 0
				for (let hour = 20; hour < 32; hour++) {
					tempHour = hour
				  for (let minute = 0; minute < 60; minute += 6) {
					if(tempHour > 24){
						tempHour = tempHour - 24
					}
					//console.log(hour)
				    let strHour = tempHour.toString().padStart(2, '0'); // 确保小时部分始终有两位数字
				    let strMinute = minute.toString().padStart(2, '0'); // 确保分钟部分始终有两位数字
				    halfHourArray.push(`${strHour}:${strMinute}`);
				  }
				}
				halfHourArray.push(`08:00`);
				//console.log(halfHourArray)
				return halfHourArray
			}
export function getOneToToday(){//获取1号跟今日
				 let today = getToday()
				 let one = today.substr(0,8)+"01"
				 
				 let weekData = getWeekDates()
				 let monthData = getDates()
				 
				 
				 let arr = {}
				 arr.today = today
				 arr.one = one
				 arr.weekend = weekData[weekData.length - 1].fullDate
				 arr.monthend = today.substr(0,8) + monthData[monthData.length - 1]
				 arr.year = today.substr(0,4)
				 //console.log("eeee",arr)
				 return arr
			}

export function getDates(timeStamp = ""){
				let today = new Date();
				//const thisDay = today.getDate()
				  if(timeStamp){
				  				  
				  				 today = new Date(timeStamp); ///获取传值日期的周
				  }
				  const year = today.getYear()
				  const month = today.getMonth() + 1
				  const nextMonth = new Date(year, month, 1);
				  // 从下个月的第一天减去一天，得到本月最后一天
				  const lastDay = new Date(nextMonth - 1);
				  // 获取本月最后一天的日期，即本月的天数
				const days = lastDay.getDate();
				
				
				let dayArr = []
				for (let i = 1; i<=days; i++) {
					dayArr.push(i)
				}
				return dayArr
			}
export function getMonthes(){
				const date = new Date();
				//const thisMonth = (date.getMonth() + 1)
				let monthArr = []
				for (let i = 1; i<=12; i++) {
					monthArr.push(i)
				}
				return monthArr
			}
			
export function toggleDate(currentDate){
				const date = new Date(currentDate);
				//console.log("eee",currentDate)
				// 获取月份和日期
				const month = date.getMonth() + 1; // getMonth() 返回的月份是从0开始的
				const day = date.getDate();
				
				// 将数字月份和日期转换为字符串，并添加前导零（如果需要）
				const strMonth = month.toString().padStart(2, '0');
				const strDay = day.toString().padStart(2, '0');
				
				// 构建最终的字符串格式
				const formattedDate = `${strMonth}月${strDay}日`;
				return formattedDate;
				//console.log(formattedDate); // 输出："8月31日"
			}

export function changeDateToHourMinute(date){
	// 给定的日期时间字符串
	//console.log(date)
	const dateTimeStr = date;
	
	// 解析日期时间字符串为Date对象
	const dateTime = new Date(dateTimeStr);
	
	// 获取小时和分钟
	const hours = dateTime.getHours();
	const minutes = dateTime.getMinutes();
	
	// 格式化小时和分钟，确保它们是两位数字
	const formattedHours = hours.toString().padStart(2, '0');
	const formattedMinutes = minutes.toString().padStart(2, '0');
	
	// 拼接成最终的字符串格式
	const timeStr = `${formattedHours}:${formattedMinutes}`;
	
	return timeStr
}

export function diffTwoDates(sdate,edate){
	// 给定的日期时间字符串
	const date1 = new Date(sdate); // 创建一个日期对象
	const date2 = new Date(edate); // 创建另一个日期对象
	
	const diff = Math.round((date2 - date1) / 60000 / 60 /24 ); // 计算时间差，以天为单位
	// if(diff < 1){
	// 	diff = 1 //最小为1
	// }
	//console.log(diff); // 输出时间差
	
	return diff
}

export function getRecentDayRange(days) {
	const today = new Date(); // 获取当前日期
    const endDate = new Date(); // 结束日期为今天
    const startDate = new Date(today.getTime() - days * 24 * 60 * 60 * 1000); // 开始日期为N天前
  
    // 格式化日期为 "YYYY-MM-DD"
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };
  
    // 获取格式化的日期字符串
    const start = formatDate(startDate);
    const end = formatDate(endDate);
  const arr = {
	  "startDate":start,
	  "endDate":end
  }

  return arr;
}
export function convertToBase64(filePath) {
	plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
	    if (entry.isFile) {
	      var fileReader = new plus.io.FileReader();
	      fileReader.onloadend = function(e) {
			  console.log(e)
	        var base64Image = e.target.result;
	        console.log(base64Image); // 这里是文件内容的Base64编码
	      };
	      fileReader.onerror = function(e) {
	        console.error('读取文件失败:', e);
	      };
	      fileReader.readAsDataURL(entry.file);
	    }
	  }, function(e) {
	    console.error('解析本地文件路径失败:', e);
	  });
  
}

export function getMonthDateRanges(year, month) {
  const weeks = [];
  const firstDay = new Date(year, month - 1, 1);
  const lastDay = new Date(year, month, 0);
  const firstDayOfWeek = firstDay.getDay();
  let startDate = new Date(firstDay);
  startDate.setDate(firstDay.getDate() - (firstDayOfWeek) % 7 );
//console.log("a",firstDayOfWeek,"b" ,(firstDayOfWeek + 6) % 7,"c",firstDay.getDate())

  while (startDate < lastDay) {
    const endDate = new Date(startDate);
	let week = ""
    endDate.setDate(endDate.getDate() + 6);
	
    if (endDate > lastDay) {
		break;
      //endDate = new Date(lastDay);
    }
	//console.log("hhhh")
	week = formatDate(new Date(startDate)) + "/" + formatDate(endDate)
	
    weeks.push(week);
    startDate = new Date(endDate);
    startDate.setDate(endDate.getDate() + 1);
	//console.log("gggg",week)
  }

  return weeks;
}

function formatDate(date) {
  // 获取月份和日期，月份减1因为getMonth()返回0-11
  const month = date.getMonth() + 1;
  const day = date.getDate();

  // 将月份和日期格式化为两位数
  const formattedMonth = month < 10 ? `0${month}` : month;
  const formattedDay = day < 10 ? `0${day}` : day;

  // 返回格式化的字符串
  return `${formattedMonth}-${formattedDay}`;
}

export function removeArrayWithName(arr,subscriptName,itemName){ //按指定名称删除元素

	// 找到名称为 'subscriptName' 的元素的下标
	let indexToRemove = array.findIndex(item => item[subscriptName] === itemName);
	
	// 如果找到了，就删除它
	if (indexToRemove !== -1) {
	  array.splice(indexToRemove, 1);
	}
	
}

export function todayToWeek(){
	const now = new Date(); // 获取当前日期和时间
    const dayOfWeek = now.getDay(); // 获取星期几，返回值为 0（周日）到 6（周六）

    // 将数字转换为对应的星期名称
    const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
    const today = weekDays[dayOfWeek];
	return today
	  //console.log(`今天是：${today}`);
}
//判断是否为对象
export function isObject(value) {
  return typeof value === 'object' && value !== null;
}

/**解密字符串 */
export function decryptString(str){
	const key = CryptoJS.enc.Utf8.parse('zhishekao2025316zhishekao2025316')
  	const iv = CryptoJS.enc.Utf8.parse('shegongkaoshi316')
	const decrypted = CryptoJS.AES.decrypt(str, key, {
	iv: iv,
	mode: CryptoJS.mode.CBC,     // 明确指定CBC模式
	padding: CryptoJS.pad.Pkcs7 // 确认填充方式
	})
	  
	  return decrypted.toString(CryptoJS.enc.Utf8)

}